<template>
  <div class="camera_outer">
    <a-row >
      <a-col :span="24">
        <a-row :gutter="12">
          <a-col :span="12">
            <div style="height:400px;border:1px dashed #ddd;overflow:hidden;">
              <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay style="overflow:hidden;" ></video>
            </div>
            <div class="pad_bot10 pad_top10">
              <a-button type="primary" class="primary_linear" @click="setImage">拍照</a-button>&emsp;
              <a-button @click="clearImage">清空</a-button>
            </div>
          </a-col>
          <a-col :span="12">
            <div style="height:400px;border:1px dashed #ddd; ">
              <div v-if="imgSrc" class="img_bg_camera">
                <img :src="imgSrc" alt="" class="tx_img">
              </div>
            </div>
            <div class="pad_bot10 pad_top10" style="color:red">{{ errorMsg }}</div>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
    <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight" ></canvas>
    <!-- <div class="btn_camera" v-if="imgSrc" @click="postSubmitPicturesData">
      {{ validTip }}上传图片
    </div>
    <div v-else class="btn_camera">把您的脸至于圆圈中央</div> -->
  </div>
</template>
<script>
import { compress } from '@/utils/util'
export default {
  name: 'Camera',
  props: {
    errorMsg: {
      type: String,
      default: ''
    }
  },
  data () {
    return {

      videoWidth: 640, // 视屏高度
      videoHeight: 400, // 视屏宽度
      imgSrc: '', // 拍照图片
      thisCancas: null, // Cancas操作对象
      thisContext: null, // Cancas绘画内容
      thisVideo: null, // video 操作对象
      validTip: '验证中' // 完成拍照后验证文字
    }
  },
  computed: {
  },
  methods: {
    /*
     *@Time 2019/10/15 0005 17:35
     *@function  调用权限
     *@本地localhost或者https
     *****************************************/
    getCompetence () {
      this.thisCancas = document.getElementById('canvasCamera')
      this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      const constraints = { audio: false, video: { width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)' } }
      navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in this.thisVideo) {
          this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          this.thisVideo.src = window.URL.createObjectURL(stream)
        }
        this.thisVideo.onloadedmetadata = (e) => {
          this.thisVideo.play()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    /*
     *@Time 2019/6/5 0005 17:32
     *@function  绘制图片
     *****************************************/
    setImage () {
      // 点击，canvas画图
      this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight)
      // 获取图片base64链接
      const image = this.thisCancas.toDataURL('image/png')
      this.imgSrc = image
      this.$emit('getFile', this.imgSrc)
    },
    clearImage () {
      this.imgSrc = ''
      this.$emit('getFile', this.imgSrc)
    },
    /*
     *@Time 2019/6/5 0005 17:44
     *@function  base64转文件
     *****************************************/
    dataURLtoFile (dataurl, filename) {
      const arr = dataurl.split(',')
      const img = new Image()
      img.src = dataurl
      const newArr = compress(img).split(',')

      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      const file = new File([u8arr], filename, { type: mime })
      return [file, newArr[1]]
    },

    /*
     *@Time 2019/6/10 0010 3:41
     *@function  关闭摄像头
     *****************************************/
    stopNavigator () {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    /*
     *@Time 2019/10/15 0010 3:41
     *@function  上传图片接口
     *****************************************/
    postSubmitPicturesData () {
      const file = this.dataURLtoFile(this.imgSrc, 'file')
      return file
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.getCompetence()
    })
  },
  beforeDestroy () {
    this.stopNavigator()
  }
}

</script>
<style lang="less" scoped>
.camera_outer{
  position: relative;
  overflow: hidden;
  background-size: 100% 100%;
  video,canvas,.tx_img{
    -moz-transform:scaleX(-1);
    -webkit-transform:scaleX(-1);
    -o-transform:scaleX(-1);
    transform:scaleX(-1);
  }
  .img_bg_camera{
    width: 100%;
    height: 100%;

    img{
     width:auto;
     height: 100%;
    }
  }

}
</style>
